package de.gwtprime.server.model;

import java.io.Serializable;
import java.util.logging.Logger;

import javax.persistence.Cacheable;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

import de.gwtprime.server.sql.helper.HibernateHelper;


/**
 * Base class of all JPA Entities
 * @author jan
 *
 */
@MappedSuperclass 
@Cacheable
public abstract class EntityBase implements Serializable{
	
	/**
	 * Serial ID
	 */
	private static final long serialVersionUID = 1;
	
	protected static Logger logger = Logger.getLogger(EntityBase.class.getName());
	
	/**
	 * Unique id
	 */
	private Long id;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public Long getId() {
		return id;
	}
	
	public void setId(Long id) {
		this.id = id;
	}
	
	
	public Long persist() {
		
		EntityManager em = HibernateHelper.beginTransactionWithoutTransaction();
		Long id = HibernateHelper.persistWithOutEntityManager(em, this);
		em.close();
		return id;
	}
	
	public void persistPure(EntityManager em) {
		HibernateHelper.persistWithOutEntityManager(em, this);
	}
	
	
	public EntityBase mergePure(EntityManager em) {
		return HibernateHelper.merge(em, this);
	}
	
	public <T extends EntityBase> T merge() {
		EntityManager em = HibernateHelper.beginTransactionWithoutTransaction();
		T entity =  (T) HibernateHelper.merge(em, this);
		em.close();
		return entity;
	}
	
	
	public void persistHibernate() {
		HibernateHelper.persistNew(this);
	}

	public void remove() {
		HibernateHelper.remove(this);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		EntityBase other = (EntityBase) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
	
	public void decreaseVoteValueAndPersist(){
	}
	
	
}
